package com.zt.bus.line.service;

import com.zt.bus.constant.BusConstant;
import com.zt.bus.line.inter.DiscountDetailMapper;
import com.zt.bus.line.inter.DiscountMapper;
import com.zt.bus.line.model.Discount;
import com.zt.bus.line.model.DiscountDetail;
import com.zt.servlet.FieldAlias;
import com.zt.servlet.ReqBean;
import com.zt.system.model.BusinessException;
import com.zt.system.model.SqlBuilder;
import com.zt.system.service.BaseService;
import com.zt.system.service.IFieldAliasService;
import com.zt.util.StringUtil;
import java.util.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class DiscountService extends BaseService implements IFieldAliasService {

    @Autowired
    private DiscountMapper discountMapper;

    @Autowired
    private DiscountDetailMapper discountDetailMapper;

    /**
     * 查询
     * 
     * @param reqBean
     * @return
     */
    @FieldAlias(service = "discountService", field = "discountId", alias = "discountDetails")
    public JSONObject getTable(ReqBean reqBean) {
        SqlBuilder sqlBuilder = new SqlBuilder("select * from DZ_DISCOUNT where C_DISCOUNT_STATUS = ?",
                BusConstant.DiscountStatus.ENABLE);
        sqlBuilder.addWhereLike2("DISCOUNT_NAME", reqBean.getInfo("discountName"));
        sqlBuilder.addWhere("C_DISCOUNT_TYPE", reqBean.getInfo("discountType"));
        sqlBuilder.addWhere("DISCOUNT_ID", reqBean.getInfo("discountId"));
        return queryTable(sqlBuilder, reqBean.getPageSize(), reqBean.getPageIndex());
    }

    /**
     * 通过id查询
     * 
     * @param discountId
     * @return
     */
    @Cacheable(value = BusConstant.Cache.DISCOUNT, key = "#discountId")
    public Discount getById(final String discountId) {
        final Discount discount = discountMapper.selectByPrimaryKey(discountId);
        if (discount != null) {
            // 排序
            List<DiscountDetail> list = discountDetailMapper.selectEnableByDiscountId(discount.getId());
            if (list != null && list.size() > 1) {
                Collections.sort(list, new Comparator<DiscountDetail>() {
                    public int compare(DiscountDetail o1, DiscountDetail o2) {
                        if (BusConstant.DiscountType.DAYS_RATE.equals(discount.getType())) {
                            return o1.getDays().compareTo(o2.getDays());
                        } else {
                            return o1.getStartDate().compareTo(o2.getStartDate());
                        }
                    }
                });
            }
            discount.setDetails(list);
        }
        return discount;
    }

    /**
     * 新增
     * 
     * @param discount
     */
    public void add(Discount discount, List<DiscountDetail> discountDetails) {
        discount.setId(intIncrementId("DZ_DISCOUNT", "DISCOUNT_ID"));// 手动设置Id
        discount.setMakeTime(new Date());
        discount.setModifyTime(discount.getMakeTime());
        discount.setStatus(BusConstant.DiscountStatus.ENABLE);
        discountMapper.insert(discount);

        if (discountDetails != null && discountDetails.size() > 0) {
            for (int i = 0; i < discountDetails.size(); i++) {
                DiscountDetail discountDetail = discountDetails.get(i);
                discountDetail.setDiscountId(discount.getId());
                discountDetail.setId(intIncrementId("DZ_DISCOUNT_DETAIL", "DISCOUNT_DETAIL_ID"));
                discountDetail.setStatus(BusConstant.DiscountDetailStatus.ENABLE);
                discountDetailMapper.insert(discountDetail);
            }
        }
    }

    /**
     * 修改
     * 
     * @param discount
     */
    @CacheEvict(value = BusConstant.Cache.DISCOUNT, allEntries = true)
    public void update(Discount discount, List<DiscountDetail> discountDetails, JSONArray deleteDiscountDetailList) {
        String discountId = discount.getId();
        if (StringUtil.isEmpty(discountId)) {
            throw new BusinessException("获取主键失败");
        }

        discount.setModifyTime(new Date());
        discountMapper.updateByPrimaryKeySelective(discount);

        if (discountDetails != null && discountDetails.size() > 0) {
            for (int i = 0; i < discountDetails.size(); i++) {
                DiscountDetail discountDetail = discountDetails.get(i);
                if (StringUtils.isBlank(discountDetail.getId())) { // 等于空，新增
                    discountDetail.setDiscountId(discount.getId());
                    discountDetail.setId(intIncrementId("DZ_DISCOUNT_DETAIL", "DISCOUNT_DETAIL_ID"));
                    discountDetail.setStatus(BusConstant.DiscountDetailStatus.ENABLE);
                    discountDetailMapper.insert(discountDetail);
                } else { // 不等于空，修改
                    DiscountDetail discountDetailBean = discountDetailMapper.selectByPrimaryKey(discountDetail.getId());
                    if (BusConstant.DiscountType.PERIOD_RATE.equals(discount.getType())) {
                        discountDetailBean.setStartDate(discountDetail.getStartDate());
                        discountDetailBean.setEndDate(discountDetail.getEndDate());
                    } else {
                        discountDetailBean.setDays(discountDetail.getDays());
                    }
                    discountDetailBean.setDiscountRate(discountDetail.getDiscountRate());
                    discountDetailBean.setStatus(discountDetail.getStatus());
                    discountDetailBean.setModifyTime(new Date());
                    discountDetailMapper.updateByPrimaryKeySelective(discountDetailBean);
                }
            }
        }

        //删除确定删除的明细
        if(deleteDiscountDetailList != null && deleteDiscountDetailList.size() > 0) {
            for (int i = 0; i < deleteDiscountDetailList.size(); i++) {
                JSONObject json = deleteDiscountDetailList.getJSONObject(i);
                deleteDetail(json.getString("discountDetailId"));
            }
        }

    }

    /**
     * 删除折扣明细
     * 
     * @param discountDetailId
     */
    @CacheEvict(value = BusConstant.Cache.DISCOUNT, allEntries = true)
    public void deleteDetail(String discountDetailId) {
        if (StringUtils.isBlank(discountDetailId)) {
            throw new BusinessException("缺少参数");
        }
        DiscountDetail detail = discountDetailMapper.selectByPrimaryKey(discountDetailId);
        detail.setStatus(BusConstant.DiscountDetailStatus.DISABLE);
        detail.setModifyTime(new Date());
        discountDetailMapper.updateByPrimaryKeySelective(detail);
    }

    @CacheEvict(value = BusConstant.Cache.DISCOUNT, allEntries = true)
    public void delete(String discountId, String userId) {
        if (StringUtils.isBlank(discountId)) {
            throw new BusinessException("缺少参数!");
        }

        Date now = new Date();
        Discount discount = discountMapper.selectByPrimaryKey(discountId);
        discount.setStatus(BusConstant.DiscountStatus.DISABLE);
        discount.setModifyTime(now);
        discountMapper.updateByPrimaryKeySelective(discount);

        List<DiscountDetail> list = discountDetailMapper.selectEnableByDiscountId(discountId);
        for (int i = 0; i < list.size(); i++) {
            DiscountDetail detail = list.get(i);
            detail.setStatus(BusConstant.DiscountDetailStatus.DISABLE);
            detail.setModifyTime(now);
            detail.setOperator(userId);
            discountDetailMapper.updateByPrimaryKeySelective(detail);
        }
    }

    /**
     * 获取详情
     * 
     * @param fields
     * @param param
     * @return
     */
    @Override
    public Map<String, Object> dealFieldAlias(List<Object> fields, String param) {
        Map<String, Object> map = new HashedMap();
        for (Object field : fields) {
            map.put((String) field, new JSONArray());
        }
        SqlBuilder sqlBuilder = new SqlBuilder("SELECT * FROM DZ_DISCOUNT_DETAIL where C_DISCOUNT_DETAIL_STATUS = ? ",
                BusConstant.DiscountDetailStatus.ENABLE).addWhereIn("DISCOUNT_ID", fields);
        JSONArray array = query(sqlBuilder);
        for (int i = 0; i < array.size(); i++) {
            JSONObject json = array.getJSONObject(i);
            String discountId = json.getString("discountId");
            ((JSONArray) map.get(discountId)).add(json);
        }
        return map;
    }
}
